import router from './router';
import { useStore } from 'vuex';
import store from '../store/index';
import { message } from 'ant-design-vue';
import { setStore, getStore } from '@/utils/store.ts';
import { getMenus } from '../api/menus';
import defaultRouter from '../router/defaultRouter';
import { Router } from 'vue-router';
const whitePathList: string[] = ['index', 'home', 'article', 'login'];

export async function createRouterGuard(router: Router) {
  router.beforeEach(async (to: any, from, next) => {
    store.commit('set_loading', true);
    const isToken = getStore({ name: 'token' });
    if (whitePathList.includes(to.name)) {
      if (isToken && to.name === 'login') {
        next('/admin');
      }
      next();
    } else {
      if (isToken) {
        if ((store as any).state.commen.menus.length && to.name !== null) {
          console.log(to, from);
          next();
        } else {
          //获取动态路由
          await store.dispatch('GENERATE_ROUTES');
          console.log(to, from);
          next({ ...to, replace: true });
        }
      } else {
        message.error('没有权限进入');
        router.push('/');
      }
    }
  });

  router.afterEach((to, from, next) => {
    store.commit('set_loading', false);
  });
}
